import {toast, wxPay} from "../../utils/tool";

let eventChannel = null
const app = getApp()
Page({
    data: {
        store: {},
        good: {},
        active: 1,
        money: 0,
        sub_price: 0,
        pay_price: 0,
        room: {},
    },
    generateGood(data) {
        const result = data.map(item => {
            const {id, num, haveSpec} = item
            const payload = {good_id: id, count: num}
            if (haveSpec) {
                payload.biaoji = item.targetSpecName
                payload.count = item.specNumber
            }
            return payload
        })
        return JSON.stringify(result)
    },
    confirmHandler() {
        const {active: pay_type, good, sub_price, pay_price, room: {id: roomID}} = this.data
        const goods_items = this.generateGood(good)
        app.ajax({
            url: '/api/food/creategoodorder',
            data: {pay_type, couponofuser_id: '', sub_price: 0, pay_price, goods_items, room_id: roomID},
            success: async resp => {
                const {code, data, msg} = resp
                if (code !== 1) return toast({title: msg})
                const [error, payRes] = await wxPay(data)
                if (error || !payRes) {
                    return toast({title: "支付失败"})
                }
                toast({title: '支付成功'}, () => {
                    wx.navigateBack({
                        success: () => {
                            const {store: {id: storeID}, room: {id: roomID}} = this.data
                            eventChannel.emit('addSuccess', {roomID, storeID})
                        }
                    })
                })
            }
        })
    }
    ,
    choseType(ev) {
        const {index} = ev.currentTarget.dataset
        if (index === this.data.active) return
        this.setData({
            active: index
        })
    },
    getOrderData({store, good, room}) {
        console.log(good, 'goodList')
        this.setData({
            good,
            store,
            room,
        })
        // let count = 0
        // const {price} = good
        // count = price * 1
        const count = good.reduce((pre, cur) => {
            let {num, price, haveSpec} = cur
            if (haveSpec) {
                num = cur.specNumber
            }
            return pre + (num * price)
        }, 0)
        this.setData({
            pay_price: count.toFixed(2)
        })
    },
    onLoad: function (options) {
        if (!!eventChannel) {
            eventChannel.off("getOrder", this.getOrderData)
            eventChannel = null
        }

        if (!eventChannel) {
            eventChannel = this.getOpenerEventChannel()
            eventChannel.on('getOrder', this.getOrderData)
        }
        const {money} = app.globalData.userInfo

        this.setData({
            money
        })
    },
    onUnload() {

    }
})
;
